package com.pearlsoft.webapp.core.dataset.factory.reflect;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.pearlsoft.commons.utils.ClassUtil;
import com.pearlsoft.webapp.core.annotation.QueryHandlerComponent;
import com.pearlsoft.webapp.core.dataset.DataSetException;
import com.pearlsoft.webapp.core.dataset.QueryHandler;
import com.pearlsoft.webapp.core.dataset.factory.AbstractQueryHandlerFactory;
import com.pearlsoft.webapp.core.dataset.spi.ContextQueryHandler;

import edu.emory.mathcs.backport.java.util.Arrays;

/**
 * 
 * ReflectQueryHandlerFactory
 * 
 * @Creator haitingr
 * @Create-DateTime 2011-12-22
 */
public class ReflectQueryHandlerFactory extends AbstractQueryHandlerFactory {

	protected static final Log logger = LogFactory.getLog(ReflectQueryHandlerFactory.class);

	protected List<String> scanPackages = new ArrayList<String>();

	protected Map<String, QueryHandler> handlers = new HashMap<String, QueryHandler>();

	@SuppressWarnings("unchecked")
	public void init() throws Exception {
		Set<Class<?>> clss = new HashSet<Class<?>>();
		for (String pkg : this.scanPackages) {
			Class<?>[] cls = ClassUtil.loadClassesFromPackage(pkg, QueryHandlerComponent.class);
			clss.addAll(Arrays.asList(cls));
		}
		for (Class<?> clazz : clss) {
			QueryHandlerComponent component = ClassUtil.getAnnotationIfAvailable(clazz, QueryHandlerComponent.class);
			QueryHandler handler = (QueryHandler) ClassUtil.instantiateClass(clazz);
			if (handler instanceof ContextQueryHandler) {
				((ContextQueryHandler) handler).setApplicationContext(context);
			}
			this.handlers.put(component.name(), handler);
			System.out.println(component.name()+","+ handler.getClass());
		}
	}

	public void setScanPackages(List<String> scanPackages) {
		this.scanPackages = scanPackages;
	}

	public QueryHandler create(String handlerName) throws DataSetException {
		return this.handlers.get(handlerName);
	}

}
